package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R

/*
* DefineRectCornerView
* */
class DefineRectCornerView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : BaseView(context, attributeSet) {

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_83CF39)
        }
    }

    private val mPath0 by lazy {
        Path()
    }

    private val rectF by lazy {
        RectF()
    }

    private var floatArr: FloatArray

    init {
        setLayerType(View.LAYER_TYPE_HARDWARE, null)

        var topLeftCorner: Float
        var topRightCorner: Float
        var bottomLeftCorner: Float
        var bottomRightCorner: Float

        context.obtainStyledAttributes(attributeSet,R.styleable.DefineRectCornerView).apply {
            topLeftCorner = getDimension(R.styleable.DefineRectCornerView_topLeftCorner, 0F)
            topRightCorner = getDimension(R.styleable.DefineRectCornerView_topRightCorner, 0F)
            bottomLeftCorner = getDimension(R.styleable.DefineRectCornerView_bottomLeftCorner, 0F)
            bottomRightCorner = getDimension(R.styleable.DefineRectCornerView_bottomRightCorner, 0F)
            recycle()
        }

        floatArr = FloatArray(8)
        floatArr[0] = topLeftCorner
        floatArr[1] = topLeftCorner

        floatArr[2] = topRightCorner
        floatArr[3] = topRightCorner

        floatArr[4] = bottomLeftCorner
        floatArr[5] = bottomLeftCorner

        floatArr[6] = bottomRightCorner
        floatArr[7] = bottomRightCorner
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBackgroundColor(context.resources.getColor(R.color.color_F3F3F3))

        rectF.set(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat())

        canvas?.apply {
            mPath0.apply {
                addRoundRect(
                    rectF,
                    floatArr,
                    Path.Direction.CW
                )
            }
            drawPath(mPath0, mPaint0)
        }
    }
}